<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">

<script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script>
<link href="//cdn.bootcss.com/pace/1.0.2/themes/pink/pace-theme-flash.css" rel="stylesheet">

<style>
    .pace .pace-progress {
        background: #1E92FB; /*进度条颜色*/
        height: 3px;
    }
    .pace .pace-progress-inner {
         box-shadow: 0 0 10px #1E92FB, 0 0 5px     #1E92FB; /*阴影颜色*/
    }
    .pace .pace-activity {
        border-top-color: #1E92FB;    /*上边框颜色*/
        border-left-color: #1E92FB;    /*左边框颜色*/
    }
</style>

  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/logo.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/hadoop_32px.ico?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/hadoop_16px.ico?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="Hbase," />





  <link rel="alternate" href="/atom.xml" title="鬼谷子" type="application/atom+xml" />






<meta name="description" content="Hbase开发入门指南">
<meta name="keywords" content="Hbase">
<meta property="og:type" content="article">
<meta property="og:title" content="Hbase开发入门指南">
<meta property="og:url" content="dengcongbao.github.io/2018/01/18/Hbase开发入门指南/index.html">
<meta property="og:site_name" content="鬼谷子">
<meta property="og:description" content="Hbase开发入门指南">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="/img/datatype.png">
<meta property="og:updated_time" content="2018-01-18T02:17:04.110Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Hbase开发入门指南">
<meta name="twitter:description" content="Hbase开发入门指南">
<meta name="twitter:image" content="/img/datatype.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":5},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="dengcongbao.github.io/2018/01/18/Hbase开发入门指南/"/>





  <title>Hbase开发入门指南 | 鬼谷子</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?90d4142adac17e4c6475a1c41a5eb0f4";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>
<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    <a href="https://github.com/DengCongBao" class="github-corner" aria-label="View source on Github"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#70B7FD; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">鬼谷子</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">鬼谷子</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archive/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-schedule">
          <a href="/schedule/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-calendar"></i> <br />
            
            日程表
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="dengcongbao.github.io/2018/01/18/Hbase开发入门指南/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="鬼谷子">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/center.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="鬼谷子">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Hbase开发入门指南</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-01-18T09:56:17+08:00">
                2018-01-18
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Hadoop/" itemprop="url" rel="index">
                    <span itemprop="name">Hadoop</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2,194
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  10
                </span>
              
            </div>
          

          
              <div class="post-description">
                  Hbase开发入门指南
              </div>
          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="1-hbase数据模型"><a href="#1-hbase数据模型" class="headerlink" title="1.  hbase数据模型"></a><a href="">1.  hbase</a>数据模型</h1><h2 id="1-1-hbase数据模型"><a href="#1-1-hbase数据模型" class="headerlink" title="1.1.  hbase数据模型"></a><a href="">1.1.  hbase</a>数据模型</h2><p><img src="/img/datatype.png" alt="img"></p>
<h3 id="1-1-1-Row-Key"><a href="#1-1-1-Row-Key" class="headerlink" title="1.1.1.  Row Key"></a><a href="">1.1.1.  Row Key</a></h3><p>与nosql数据库们一样,row key是用来检索记录的主键。访问HBASE table中的行，只有三种方式：</p>
<p>1.通过单个row key访问</p>
<p>2.通过row key的range（正则）</p>
<p>3.全表扫描</p>
<p>Row key行键 (Row key)可以是任意字符串(最大长度 是 64KB，实际应用中长度一般为10-100bytes)，在HBASE内部，row key保存为字节数组。存储时，数据按照Rowkey的字典序(byte order)排序存储。设计key时，要充分排序存储这个特性，将经常一起读取的行存储放到一起。(位置相关性)</p>
<h3 id="1-1-2-Columns-Family"><a href="#1-1-2-Columns-Family" class="headerlink" title="1.1.2.  Columns Family"></a><a href="">1.1.2.  Columns Family</a></h3><p>列簇：HBASE表中的每个列，都归属于某个列族。列族是表的schema的一部分(而列不是)，必须在使用表之前定义。列名都以列族作为前缀。例如courses:history，courses:math都属于courses 这个列族。</p>
<h3 id="1-1-3-Cell"><a href="#1-1-3-Cell" class="headerlink" title="1.1.3.  Cell"></a><a href="">1.1.3.  Cell</a></h3><p>由{row key, columnFamily, version} 唯一确定的单元。cell中 的数据是没有类型的，全部是字节码形式存贮。</p>
<p>关键字：无类型、字节码</p>
<h3 id="1-1-4-Time-Stamp"><a href="#1-1-4-Time-Stamp" class="headerlink" title="1.1.4.  Time Stamp"></a><a href="">1.1.4.  Time Stamp</a></h3><p>HBASE 中通过rowkey和columns确定的为一个存贮单元称为cell。每个 cell都保存 着同一份数据的多个版本。版本通过时间戳来索引。时间戳的类型是 64位整型。时间戳可以由HBASE(在数据写入时自动 )赋值，此时时间戳是精确到毫秒的当前系统时间。时间戳也可以由客户显式赋值。如果应用程序要避免数据版本冲突，就必须自己生成具有唯一性的时间戳。每个 cell中，不同版本的数据按照时间倒序排序，即最新的数据排在最前面。</p>
<p>为了避免数据存在过多版本造成的的管理 (包括存贮和索引)负担，HBASE提供 了两种数据版本回收方式。一是保存数据的最后n个版本，二是保存最近一段 时间内的版本（比如最近七天）。用户可以针对每个列族进行设置。</p>
<h1 id="2-hbase命令"><a href="#2-hbase命令" class="headerlink" title="2.  hbase命令"></a><a href="">2.  hbase</a>命令</h1><h2 id="2-1-命令的进退"><a href="#2-1-命令的进退" class="headerlink" title="2.1.  命令的进退"></a><a href="">2.1.  命令的进退</a></h2><p>1、hbase提供了一个shell的终端给用户交互</p>
<p>#$HBASE_HOME/bin/hbase shell </p>
<p>2、如果退出执行quit命令</p>
<p>#$HBASE_HOME/bin/hbase shell</p>
<p>……</p>
<p>>quit</p>
<h2 id="2-2-命令"><a href="#2-2-命令" class="headerlink" title="2.2.  命令"></a><a href="">2.2.  命令</a></h2><table>
<thead>
<tr>
<th><strong>名称</strong></th>
<th><strong>命令表达式</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>创建表</strong></td>
<td><strong>create ‘**</strong>表名’, ‘<strong><strong>列族名1’,’</strong></strong>列族名2’,’<strong>**列族名N’</strong></td>
</tr>
<tr>
<td><strong>查看所有表</strong></td>
<td><strong>list</strong></td>
</tr>
<tr>
<td><strong>描述表</strong></td>
<td><strong>describe  **</strong>‘表名’**</td>
</tr>
<tr>
<td>判断表存在</td>
<td>exists  ‘表名’<em>**</em></td>
</tr>
<tr>
<td>判断是否禁用启用表<em>**</em></td>
<td>is_enabled ‘表名’  is_disabled ‘表名’</td>
</tr>
<tr>
<td><strong>添加记录      </strong></td>
<td><strong>put   **</strong>‘表名’, <strong><strong>‘rowKey</strong></strong>’, <strong><strong>‘列族 : </strong></strong>列‘  ,  ‘<strong>**值’</strong></td>
</tr>
<tr>
<td><strong>查看记录rowkey**</strong>下的所有数据**</td>
<td><strong>get   ‘**</strong>表名’ , ‘rowKey’**</td>
</tr>
<tr>
<td><strong>查看表中的记录总数</strong></td>
<td><strong>count   ‘**</strong>表名’**</td>
</tr>
<tr>
<td><strong>获取某个列族</strong></td>
<td>get ‘表名’,’rowkey’,’列族’<em>**</em></td>
</tr>
<tr>
<td><strong>获取某个列族的某个列</strong></td>
<td>get ‘表名’,’rowkey’,’列族：列’</td>
</tr>
<tr>
<td><strong>删除记录</strong></td>
<td><strong>delete   **</strong>‘表名’ ,<strong><strong>‘行名’ , </strong></strong>‘列族：列’**</td>
</tr>
<tr>
<td><strong>删除整行</strong></td>
<td><strong>deleteall ‘**</strong>表名’,’rowkey’**</td>
</tr>
<tr>
<td><strong>删除一张表</strong></td>
<td><strong>先要屏蔽该表，才能对该表进行删除</strong>  <strong>第一步 disable **</strong>‘表名’ <strong><strong>，第二步  drop ‘</strong></strong>表名’**</td>
</tr>
<tr>
<td><strong>清空表</strong></td>
<td><strong>truncate ‘**</strong>表名’**</td>
</tr>
<tr>
<td><strong>查看所有记录</strong></td>
<td><strong>scan “**</strong>表名”  **</td>
</tr>
<tr>
<td><strong>查看某个表某个列中所有数据</strong></td>
<td><strong>scan “**</strong>表名” ,  {COLUMNS=&gt;’<strong><strong>列族名:</strong></strong>列名’}**</td>
</tr>
<tr>
<td><strong>更新记录  </strong></td>
<td><strong>就是重写一遍，进行覆盖，hbase**</strong>没有修改，都是追加**</td>
</tr>
</tbody>
</table>
<h1 id="3-hbase依赖zookeeper"><a href="#3-hbase依赖zookeeper" class="headerlink" title="3.  hbase依赖zookeeper"></a><a href="">3.  hbase</a>依赖zookeeper</h1><p>zookeeper的作用：</p>
<p>1、  保存Hmaster的地址和backup-master地址</p>
<p>hmaster的作用：</p>
<p>a)      管理HregionServer</p>
<p>b)     做增删改查表的节点</p>
<p>c)      管理HregionServer中的表分配</p>
<p>2、  保存表-ROOT-的地址</p>
<p>hbase默认的根表，检索表。</p>
<p>3、  HRegionServer列表</p>
<p>表的增删改查数据。</p>
<p>和hdfs交互，存取数据。</p>
<h1 id="4-hbase开发"><a href="#4-hbase开发" class="headerlink" title="4.  hbase开发"></a><a href="">4.  hbase</a>开发</h1><h2 id="4-1-配置"><a href="#4-1-配置" class="headerlink" title="4.1.  配置"></a><a href="">4.1.  配置</a></h2><p>HBaseConfiguration</p>
<p>包：org.apache.hadoop.hbase.HBaseConfiguration</p>
<p>作用：通过此类可以对HBase进行配置</p>
<p>用法实例：</p>
<p>Configuration config =HBaseConfiguration.create();</p>
<p>说明：HBaseConfiguration.create() 默认会从classpath 中查找hbase-site.xml 中的配置信息，初始化 Configuration。</p>
<p>使用方法:</p>
<p>static Configuration config = null;</p>
<p>static {</p>
<p>​    config = HBaseConfiguration.create();</p>
<p>​    config.set(“hbase.zookeeper.quorum”,”slave1,slave2,slave3”);</p>
<p>​    config.set(“hbase.zookeeper.property.clientPort”,”2181”);</p>
<p>}</p>
<h2 id="4-2-表管理类"><a href="#4-2-表管理类" class="headerlink" title="4.2.  表管理类"></a><a href="">4.2.  表管理类</a></h2><p>HBaseAdmin</p>
<p>包：org.apache.hadoop.hbase.client.HBaseAdmin</p>
<p>作用：提供接口关系HBase 数据库中的表信息</p>
<p>用法：</p>
<p>HBaseAdmin admin = new HBaseAdmin(config);</p>
<h2 id="4-3-表描述类"><a href="#4-3-表描述类" class="headerlink" title="4.3.  表描述类"></a><a href="">4.3.  表描述类</a></h2><p>HTableDescriptor</p>
<p>包：org.apache.hadoop.hbase.HTableDescriptor</p>
<p>作用：HTableDescriptor 类包含了表的名字以及表的列族信息</p>
<p>​         表的schema（设计）</p>
<p>用法：</p>
<p>HTableDescriptor htd =newHTableDescriptor(tablename);</p>
<p>htd.addFamily(newHColumnDescriptor(“myFamily”));</p>
<h2 id="4-4-列族的描述类"><a href="#4-4-列族的描述类" class="headerlink" title="4.4.  列族的描述类"></a><a href="">4.4.  列族的描述类</a></h2><p>HColumnDescriptor</p>
<p>包：org.apache.hadoop.hbase.HColumnDescriptor</p>
<p>作用：HColumnDescriptor 维护列族的信息</p>
<p>用法：</p>
<p>htd.addFamily(newHColumnDescriptor(“myFamily”));</p>
<h2 id="4-5-创建表的操作"><a href="#4-5-创建表的操作" class="headerlink" title="4.5.  创建表的操作"></a><a href="">4.5.  创建表的操作</a></h2><p>CreateTable（一般我们用shell创建表）</p>
<p>static Configuration config = null;</p>
<p>static {</p>
<p>​    config = HBaseConfiguration.create();</p>
<p>​    config.set(“hbase.zookeeper.quorum”,”slave1,slave2,slave3”);</p>
<p>​    config.set(“hbase.zookeeper.property.clientPort”,”2181”);</p>
<p>}</p>
<p>HBaseAdmin admin = new HBaseAdmin(config);</p>
<p>HTableDescriptor desc = newHTableDescriptor(tableName);</p>
<p>HColumnDescriptor family1 = newHColumnDescriptor(“f1”);</p>
<p>HColumnDescriptor family2 = new HColumnDescriptor(“f2”);</p>
<p>desc.addFamily(family1);</p>
<p>desc.addFamily(family2);</p>
<p>admin.createTable(desc);</p>
<h2 id="4-6-删除表"><a href="#4-6-删除表" class="headerlink" title="4.6.  删除表"></a><a href="">4.6.  删除表</a></h2><p>HBaseAdmin admin = new HBaseAdmin(config);</p>
<p>admin.disableTable(tableName);</p>
<p>admin.deleteTable(tableName);</p>
<h2 id="4-7-创建一个表的类"><a href="#4-7-创建一个表的类" class="headerlink" title="4.7.  创建一个表的类"></a><a href="">4.7.  创建一个表的类</a></h2><p>HTable</p>
<p>包：org.apache.hadoop.hbase.client.HTable</p>
<p>作用：HTable 和 HBase 的表通信</p>
<p>用法：</p>
<p>// 普通获取表</p>
<p> HTable table = newHTable(config,Bytes.toBytes(tablename);</p>
<p>// 通过连接池获取表</p>
<p>HTablePool pool = new HTablePool(config,1000);</p>
<p>HTableInterface table =pool.getTable(tableName);</p>
<h2 id="4-8-单条插入数据"><a href="#4-8-单条插入数据" class="headerlink" title="4.8.  单条插入数据"></a><a href="">4.8.  单条插入数据</a></h2><p>Put</p>
<p>包：org.apache.hadoop.hbase.client.Put</p>
<p>作用：插入数据</p>
<p>用法：</p>
<p>Put put = new Put(row);</p>
<p>p.add(family,qualifier,value);</p>
<p>说明：向表 tablename 添加“family,qualifier,value”指定的值。</p>
<p>示例代码：</p>
<p>HTablePool pool = new HTablePool(config,1000);</p>
<p>HTableInterface  table = pool.getTable(tableName);</p>
<p>Put put = new Put(Bytes.toBytes(rowKey));</p>
<p>put.add(Bytes.toBytes(family),Bytes.toBytes(qualifier),Bytes.toBytes(value));</p>
<p>table.put(put);</p>
<h2 id="4-9-批量插入"><a href="#4-9-批量插入" class="headerlink" title="4.9.  批量插入"></a><a href="">4.9.  批量插入</a></h2><p>批量插入</p>
<p>List<put> list = newArrayList<put>();</put></put></p>
<p>Put put = new Put(Bytes.toBytes(rowKey));//获取put，用于插入</p>
<p>put.add(Bytes.toBytes(family),Bytes.toBytes(qualifier),Bytes.toBytes(value));//封装信息</p>
<p>list.add(put);</p>
<p>table.put(list);//添加记录</p>
<h2 id="4-10-删除数据"><a href="#4-10-删除数据" class="headerlink" title="4.10.   删除数据"></a><a href="">4.10.   删除数据</a></h2><p>Delete</p>
<p>包：org.apache.hadoop.hbase.client.Delete</p>
<p>作用：删除给定rowkey的数据</p>
<p>用法：</p>
<p>Delete del= newDelete(Bytes.toBytes(rowKey));</p>
<p>table.delete(del);</p>
<p>代码实例</p>
<p>HTablePool pool = new HTablePool(config,1000);</p>
<p>HTableInterface  table = pool.getTable(tableName);</p>
<p>Delete del= newDelete(Bytes.toBytes(rowKey));</p>
<p>table.delete(del);</p>
<h2 id="4-11-单条查询"><a href="#4-11-单条查询" class="headerlink" title="4.11.   单条查询"></a><a href="">4.11.   单条查询</a></h2><p>Get</p>
<p>包：org.apache.hadoop.hbase.client.Get</p>
<p>作用：获取单个行的数据</p>
<p>用法：</p>
<p>HTable table = new HTable(config,Bytes.toBytes(tablename));</p>
<p>Get get = new Get(Bytes.toBytes(row));</p>
<p>Result result = table.get(get);</p>
<p>说明：获取 tablename 表中 row 行的对应数据</p>
<p>代码示例：</p>
<p>HTablePool pool = new HTablePool(config,1000);</p>
<p>HTableInterface  table = pool.getTable(tableName);</p>
<p>Get get = new Get(rowKey.getBytes());</p>
<p>Result row = table.get(get);</p>
<p>for (KeyValue kv : row.raw()) {</p>
<p>​         System.out.print(newString(kv.getRow()) + “ “);</p>
<p>​         System.out.print(newString(kv.getFamily()) + “:”);</p>
<p>​         System.out.print(newString(kv.getQualifier()) + “ = “);</p>
<p>​         System.out.print(newString(kv.getValue()));</p>
<p>​         System.out.print(“timestamp = “ + kv.getTimestamp() + “\n”);</p>
<p>}</p>
<h2 id="4-12-批量查询"><a href="#4-12-批量查询" class="headerlink" title="4.12.   批量查询"></a><a href="">4.12.   批量查询</a></h2><p>ResultScanner</p>
<p>包：org.apache.hadoop.hbase.client.ResultScanner</p>
<p>作用：获取值的接口</p>
<p>用法：</p>
<p>ResultScanner scanner =table.getScanner(scan);</p>
<p>For(Result rowResult : scanner){</p>
<p>​       Bytes[] str = rowResult.getValue(family,column);</p>
<p>}</p>
<p>说明：循环获取行中列值。</p>
<p>代码示例：</p>
<p>HTablePool pool = new HTablePool(config,1000);</p>
<p>HTableInterface table =pool.getTable(tableName);</p>
<p>Scan scan = new Scan();</p>
<p>scan.setStartRow(“a1”.getBytes());</p>
<p>scan.setStopRow(“a20”.getBytes());</p>
<p>ResultScanner scanner =table.getScanner(scan);</p>
<p>for (Result row : scanner) {</p>
<p>​         System.out.println(“\nRowkey:” + new String(row.getRow()));</p>
<p>​         for(KeyValue kv : row.raw()) {</p>
<p>​              System.out.print(new String(kv.getRow()) +” “);</p>
<p>​              System.out.print(newString(kv.getFamily()) + “:”);</p>
<p>​              System.out.print(newString(kv.getQualifier()) + “ = “);</p>
<p>​              System.out.print(newString(kv.getValue()));</p>
<p>​              System.out.print(“ timestamp = “+ kv.getTimestamp() + “\n”);</p>
<p>​         }</p>
<p>}</p>
<h2 id="4-13-hbase过滤器"><a href="#4-13-hbase过滤器" class="headerlink" title="4.13.   hbase过滤器"></a><a href="">4.13.   hbase</a>过滤器</h2><h3 id="4-13-1-FilterList"><a href="#4-13-1-FilterList" class="headerlink" title="4.13.1.           FilterList"></a><a href="">4.13.1.           FilterList</a></h3><p>FilterList 代表一个过滤器列表，可以添加多个过滤器进行查询，多个过滤器之间的关系有：</p>
<p>与关系（符合所有）：FilterList.Operator.MUST_PASS_ALL</p>
<p>或关系（符合任一）：FilterList.Operator.MUST_PASS_ONE</p>
<p>使用方法：</p>
<p>FilterList filterList = new FilterList(FilterList.Operator.MUST_PASS_ONE);   </p>
<p>Scan s1 = new Scan();  </p>
<p> filterList.addFilter(new SingleColumnValueFilter(Bytes.toBytes(“f1”),  Bytes.toBytes(“c1”),  CompareOp.EQUAL,Bytes.toBytes(“v1”) )  );  </p>
<p>filterList.addFilter(new SingleColumnValueFilter(Bytes.toBytes(“f1”),  Bytes.toBytes(“c2”),  CompareOp.EQUAL,Bytes.toBytes(“v2”) )  );  </p>
<p> // 添加下面这一行后，则只返回指定的cell，同一行中的其他cell不返回  </p>
<p> s1.addColumn(Bytes.toBytes(“f1”), Bytes.toBytes(“c1”));  </p>
<p> s1.setFilter(filterList);  //设置filter</p>
<p> ResultScanner ResultScannerFilterList = table.getScanner(s1);  //返回结果列表</p>
<h3 id="4-13-2-过滤器的种类"><a href="#4-13-2-过滤器的种类" class="headerlink" title="4.13.2.           过滤器的种类"></a><a href="">4.13.2.           过滤器的种类</a></h3><p>过滤器的种类：</p>
<p>列值过滤器—SingleColumnValueFilter </p>
<p>​     过滤列植的相等、不等、范围等</p>
<p>列名前缀过滤器—ColumnPrefixFilter </p>
<p>​     过滤指定前缀的列名</p>
<p>多个列名前缀过滤器—MultipleColumnPrefixFilter</p>
<p>​      过滤多个指定前缀的列名</p>
<p>rowKey过滤器—RowFilter</p>
<p>​     通过正则，过滤rowKey值。</p>
<h3 id="4-13-3-列植过滤器—SingleColumnValueFilter"><a href="#4-13-3-列植过滤器—SingleColumnValueFilter" class="headerlink" title="4.13.3.           列植过滤器—SingleColumnValueFilter"></a><a href="">4.13.3.           列植过滤器—SingleColumnValueFilter</a></h3><p>SingleColumnValueFilter 列值判断</p>
<p>相等 (CompareOp.EQUAL ), </p>
<p>不等(CompareOp.NOT_EQUAL),</p>
<p>范围 (e.g., CompareOp.GREATER)…………</p>
<p>下面示例检查列值和字符串’values’ 相等…</p>
<p>SingleColumnValueFilter f = new  SingleColumnValueFilter(</p>
<p>​                            Bytes.toBytes(“cFamily”)                                                Bytes.toBytes(“column”),                      CompareFilter.CompareOp.EQUAL,</p>
<p>​       Bytes.toBytes(“values”));</p>
<p>s1.setFilter(f);</p>
<p>注意：如果过滤器过滤的列在数据表中有的行中不存在，那么这个过滤器对此行无法过滤。</p>
<h3 id="4-13-4-列名前缀过滤器—ColumnPrefixFilter"><a href="#4-13-4-列名前缀过滤器—ColumnPrefixFilter" class="headerlink" title="4.13.4.           列名前缀过滤器—ColumnPrefixFilter"></a><a href="">4.13.4.           列名前缀过滤器—ColumnPrefixFilter</a></h3><p>过滤器—ColumnPrefixFilter </p>
<p>ColumnPrefixFilter 用于指定列名前缀值相等</p>
<p>ColumnPrefixFilter f = newColumnPrefixFilter(Bytes.toBytes(“values”));</p>
<p>s1.setFilter(f);</p>
<h3 id="4-13-5-多个列值前缀过滤器—MultipleColumnPrefixFilter"><a href="#4-13-5-多个列值前缀过滤器—MultipleColumnPrefixFilter" class="headerlink" title="4.13.5.           多个列值前缀过滤器—MultipleColumnPrefixFilter"></a><a href="">4.13.5.           多个列值前缀过滤器—MultipleColumnPrefixFilter</a></h3><p>MultipleColumnPrefixFilter 和ColumnPrefixFilter 行为差不多，但可以指定多个前缀</p>
<p>byte[][] prefixes = new byte[][]{Bytes.toBytes(“value1”),Bytes.toBytes(“value2”)};</p>
<p>Filter f = newMultipleColumnPrefixFilter(prefixes);</p>
<p>s1.setFilter(f);</p>
<h3 id="4-13-6-rowKey过滤器—RowFilter"><a href="#4-13-6-rowKey过滤器—RowFilter" class="headerlink" title="4.13.6.           rowKey过滤器—RowFilter"></a><a href="">4.13.6.           rowKey</a>过滤器—RowFilter</h3><p>RowFilter 是rowkey过滤器</p>
<p>通常根据rowkey来指定范围时，使用scan扫描器的StartRow和StopRow方法比较好。</p>
<p>Filter f = newRowFilter(CompareFilter.CompareOp.EQUAL, new RegexStringComparator(“^1234”));//匹配以1234开头的rowkey</p>
<p>s1.setFilter(f);</p>

      
    </div>
    
    
    
    <div>
      
        
      
    </div>
    
 <div>
     
      <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>
     
  </div>
    

    
 
    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Hbase/" rel="tag"> <i class="fa fa-tag"></i> Hbase</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/01/17/MapReduce运行原理详解/" rel="next" title="MapReduce运行原理详解">
                <i class="fa fa-chevron-left"></i> MapReduce运行原理详解
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/01/18/Hbase原理浅谈/" rel="prev" title="Hbase原理浅谈">
                Hbase原理浅谈 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/center.jpg"
                alt="鬼谷子" />
            
              <p class="site-author-name" itemprop="name">鬼谷子</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archive/">
              
                  <span class="site-state-item-count">26</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">17</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          <div class="links-of-author motion-element">
            
              
                <span class="links-of-author-item">
                  <a href="https://github.com/DengCongBao" target="_blank" title="GitHub">
                    
                      <i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:dengcongbao@yeah.net" target="_blank" title="E-Mail">
                    
                      <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://plus.google.com/guiguzi2020" target="_blank" title="Google">
                    
                      <i class="fa fa-fw fa-google"></i>Google</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://twitter.com/dengcongbao" target="_blank" title="Twitter">
                    
                      <i class="fa fa-fw fa-twitter"></i>Twitter</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://weibo.com/5602018424" target="_blank" title="Weibo">
                    
                      <i class="fa fa-fw fa-weibo"></i>Weibo</a>
                </span>
              
            
          </div>

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#1-hbase数据模型"><span class="nav-number">1.</span> <span class="nav-text">1.  hbase数据模型</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-1-hbase数据模型"><span class="nav-number">1.1.</span> <span class="nav-text">1.1.  hbase数据模型</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-1-Row-Key"><span class="nav-number">1.1.1.</span> <span class="nav-text">1.1.1.  Row Key</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-2-Columns-Family"><span class="nav-number">1.1.2.</span> <span class="nav-text">1.1.2.  Columns Family</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-3-Cell"><span class="nav-number">1.1.3.</span> <span class="nav-text">1.1.3.  Cell</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-4-Time-Stamp"><span class="nav-number">1.1.4.</span> <span class="nav-text">1.1.4.  Time Stamp</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#2-hbase命令"><span class="nav-number">2.</span> <span class="nav-text">2.  hbase命令</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#2-1-命令的进退"><span class="nav-number">2.1.</span> <span class="nav-text">2.1.  命令的进退</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-2-命令"><span class="nav-number">2.2.</span> <span class="nav-text">2.2.  命令</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#3-hbase依赖zookeeper"><span class="nav-number">3.</span> <span class="nav-text">3.  hbase依赖zookeeper</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#4-hbase开发"><span class="nav-number">4.</span> <span class="nav-text">4.  hbase开发</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#4-1-配置"><span class="nav-number">4.1.</span> <span class="nav-text">4.1.  配置</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-2-表管理类"><span class="nav-number">4.2.</span> <span class="nav-text">4.2.  表管理类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-3-表描述类"><span class="nav-number">4.3.</span> <span class="nav-text">4.3.  表描述类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-4-列族的描述类"><span class="nav-number">4.4.</span> <span class="nav-text">4.4.  列族的描述类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-5-创建表的操作"><span class="nav-number">4.5.</span> <span class="nav-text">4.5.  创建表的操作</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-6-删除表"><span class="nav-number">4.6.</span> <span class="nav-text">4.6.  删除表</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-7-创建一个表的类"><span class="nav-number">4.7.</span> <span class="nav-text">4.7.  创建一个表的类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-8-单条插入数据"><span class="nav-number">4.8.</span> <span class="nav-text">4.8.  单条插入数据</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-9-批量插入"><span class="nav-number">4.9.</span> <span class="nav-text">4.9.  批量插入</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-10-删除数据"><span class="nav-number">4.10.</span> <span class="nav-text">4.10.   删除数据</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-11-单条查询"><span class="nav-number">4.11.</span> <span class="nav-text">4.11.   单条查询</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-12-批量查询"><span class="nav-number">4.12.</span> <span class="nav-text">4.12.   批量查询</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-13-hbase过滤器"><span class="nav-number">4.13.</span> <span class="nav-text">4.13.   hbase过滤器</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-13-1-FilterList"><span class="nav-number">4.13.1.</span> <span class="nav-text">4.13.1.           FilterList</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-13-2-过滤器的种类"><span class="nav-number">4.13.2.</span> <span class="nav-text">4.13.2.           过滤器的种类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-13-3-列植过滤器—SingleColumnValueFilter"><span class="nav-number">4.13.3.</span> <span class="nav-text">4.13.3.           列植过滤器—SingleColumnValueFilter</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-13-4-列名前缀过滤器—ColumnPrefixFilter"><span class="nav-number">4.13.4.</span> <span class="nav-text">4.13.4.           列名前缀过滤器—ColumnPrefixFilter</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-13-5-多个列值前缀过滤器—MultipleColumnPrefixFilter"><span class="nav-number">4.13.5.</span> <span class="nav-text">4.13.5.           多个列值前缀过滤器—MultipleColumnPrefixFilter</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-13-6-rowKey过滤器—RowFilter"><span class="nav-number">4.13.6.</span> <span class="nav-text">4.13.6.           rowKey过滤器—RowFilter</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
         <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">鬼谷子</span>

  
</div>






 <!-- <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.3</div> -->




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.3"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  

  

  


</body>
</html>
